package com.generator.database.readwriteseparate;

import java.lang.reflect.Method;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import lombok.extern.slf4j.Slf4j;
/**
 * 基于AOP从DAO方法读取注解，实现切数据源
 * 2018-4-24 11:02:51
 * @author chenjinlong
 */
@Slf4j
public class SwitchDataSourceMethodInterceptor implements MethodInterceptor {

	
	@Override
	public Object invoke(MethodInvocation methodInvocation) throws Throwable {
		Class<?>[] clazzes = methodInvocation.getThis().getClass().getInterfaces();
		Class<?> clazz = clazzes[0];
		
		Method method = methodInvocation.getMethod();
		DataSourceSign dataSourceSign = method.getAnnotation(DataSourceSign.class);
		if(dataSourceSign != null) {
			String sign = dataSourceSign.sign();
			DynamicDataSourceHolder.setDataSourceKey(sign);
		}
		else {
			DynamicDataSourceHolder.setDataSourceKey(DynamicDataSourceHolder.MASTER_DATASOURCE);
		}
		log.info("MethodInterceptor切换数据源，className : [{}], methodName : [{}]，数据源信息：[{}]",
				clazz.getName(),
				method.getName(),
				DynamicDataSourceHolder.getDataSourceKey());
		
		Object resultObject = methodInvocation.proceed();
		
		DynamicDataSourceHolder.clearDataSourceKey();
		return resultObject;
	}
}